package com.book.servlet.manage;

import com.book.entity.Borrow;
import com.book.entity.User;
import com.book.service.BookService;
import com.book.service.BorrowService;
import com.book.service.StudentService;
import com.book.service.impl.BookServiceImpl;
import com.book.service.impl.BorrowServiceImpl;
import com.book.service.impl.StudentServiceImpl;
import com.book.utils.ThymeleafUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.util.List;

@WebServlet("/index")
public class BorrowServlet extends HttpServlet {
    BorrowService borrowService;
    StudentService studentService;
    BookService bookService;

    @Override
    public void init() throws ServletException {
        borrowService = new BorrowServiceImpl();
        bookService = new BookServiceImpl();
        studentService = new StudentServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Context context = new Context();
        List<Borrow> borrowList = borrowService.getBorrowList();
        // 从session中获取用户昵称
        User user = (User)req.getSession().getAttribute("user");
        String nickName =user.getNickname();
        // 创建Thymeleaf模板的Context对象用来向Html传递数据
        context.setVariable("nickName",nickName);
        context.setVariable("borrowList", borrowList);

        Integer bookNum = bookService.countBooks();
        Integer studentNum = studentService.countStudents();
        Integer borrowNum = borrowService.countBorrow();
        context.setVariable("bookNum", bookNum);
        context.setVariable("studentNum", studentNum);
        context.setVariable("borrowNum", borrowNum);
        ThymeleafUtil.process("index.html",context,resp.getWriter());
    }
}
